package com.itheima.travel.controller;


import com.itheima.travel.domain.ResultInfo;
import com.itheima.travel.domain.User;
import com.itheima.travel.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @RequestMapping("/register")
    public ResultInfo register(@RequestBody User user, String smsCode) {
        return userService.register(user, smsCode);
    }

    @RequestMapping("/sendSms")
    public ResultInfo sendSms(String telephone) {
        //String authCode = RandomStringUtils.randomNumeric(6);

        ResultInfo resultInfo = userService.sendSms(telephone);
        return resultInfo;
    }

    @RequestMapping("/loginSendMessage")
    public ResultInfo loginSendMessage(String username) {
        User user = userService.findByUsername(username);
        if (user == null) {
            return new ResultInfo(false, "用户名不存在！");
        }
        //String authCode = RandomStringUtils.randomNumeric(6);
        ResultInfo resultInfo = userService.sendSms(user.getTelephone());
        return resultInfo;
    }

    @RequestMapping("/login")
    public ResultInfo login(@RequestBody Map<String, String> param, HttpSession session) {
        ResultInfo resultInfo = userService.login(param);
        if (resultInfo.getSuccess()) {
            session.setAttribute("user", resultInfo.getData());
        }
        return resultInfo;
    }

    @RequestMapping("/isLogged")
    public ResultInfo isLogged(HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user==null){
            return new ResultInfo(false,"未登录");
        }else {
            return new ResultInfo(true,user);
        }
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.invalidate();
    }


    @RequestMapping("/personal")
    public User getPersonal(HttpSession session){
        User user = (User) session.getAttribute("user");
        return userService.getPersonal(user.getUid());
    }

    @RequestMapping("/updatePersonal")
    public void updatePersonal(HttpSession session,String nickname, String sex, String birthday, String email){
        User user = (User) session.getAttribute("user");
        userService.updatePersonal(nickname,sex,birthday,email,user.getUsername());
    }


}
